<template>
    <div class="box">
        <div class="header">
            <el-button type="primary" :icon="Plus" solid @click="openDialog">添加网红小店</el-button>
        </div>
        <div class="content">
            <el-table :data="tableData" border style="width: 100%;">
                <el-table-column prop="name" label="名字" width="180" />
                <el-table-column prop="address" label="地址" />
                <el-table-column prop="url" label="小店图片">
                    <template #default="scope">
                        <img class="whxd-img" :src="scope.row.url[0]" alt="">
                    </template>
                </el-table-column>
                <!-- 小店标签 -->
                <el-table-column proos="label" label="小店标签">
                    <template #default="scope">
                        <le-tag v-for="(item,index) in scope.row.label" :key="index" type="warning">{{ item }}</le-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="businessHours" label="营业时间" />
                <el-table-column prop="label" label="操作">
                    <template #default="scope">
                        <el-button type="success" :icon="Edit" @click="openDialog('edit',scope.row)">修改</el-button>
                        <el-button type="danger" :icon="Delete" @click="deleteItem(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        
    </div>
    <el-dialog v-model="whxdVisible" :title="dialogType === 'add' ? '新增网红小店' : '编辑网红小店'" width="500" center >
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" label-width="auto">
            <el-form-item label="店铺名称" prop="name">
                <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="店铺地址" prop="addres">
                <el-input v-model="ruleForm.address" type="textarea" />
            </el-form-item>
            <el-form-item label="营业时间" prop="businessHours">
                <el-time-select v-model="ruleForm.startTime" style="width: 140px;" :max-time="ruleForm.endTime"
                placeholder="开始时间" start="00:00" step="00:30" end="23:59"/>
                <el-time-select v-model="ruleForm.endTime" style="width: 140px;" :min-time="ruleForm.startTime"
                placeholder="结束时间" start="00:00" step="00:30" end="23:59"/>
            </el-form-item>
            <el-form-item label="店铺标签" prop="label">
                <el-input-tag v-model="ruleForm.label" placeholder="请输入标签" aria-label="请输入后敲击回车" />
            </el-form-item>
            <el-form-item label="店铺介绍" prop="remark">
                <el-input v-model="ruleForm.remark" type="textarea" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="registerTransform(fuleFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
<script setup>
import { Plus,Delete,Edit } from '@element-plus/icons-vue'
import data from "@/utils/data";
import { ref,onMounted } from "vue";
import { tourEmits } from 'element-plus';
const tableData = ref(data);
console.log(data,'data');
const whxdVisible =ref(false);
//表单用于双向绑定的原始数据
const ruleFormRef = ref()
const ruleForm = ref({
        name:'',
        address:'',
        startTime:'',
        endTime:'',
        urlList:[],
        label:[],
})



//通过新增按钮打开对话框

//判断是修改还是新增数据
const dialogType =ref('add')
//判断是更改数据是否有id 有id就是修改，没有id就是新增
const whxdId =ref(null)

//模板语法用``
const name = '老师'
//构造新数据对象
const aaa = `我是一个老师,我叫: ${name}`
const aaaa= '我是一个老师,我叫:' + name
console.log('aaa',aaa);
console.log('aaaa',aaaa);



//添加type参数，用于判断是添加还是修改
const openDialog = (type, row) => {
    //初始化表单数据
    ruleForm.value = {
        name:'',
        address:'',
        startTime:'',
        endTime:'',
        urlList:[],
        label:[],
    }
    whxdVisible.value = true;
    console.log('type----', type);
    console.log('row----', row);

    //判断是修改还是新增
    if (type == 'edit') {
        dialogType.value = 'edit'
        ruleForm.value = {...row}
        //将营业时间拆分为开始时间和结束时间
        ruleForm.value.startTime = row.businessHours.split('-')[0]
        ruleForm.value.endTime = row.businessHours.split('-')[1]
        whxdId.value = row.id
    }else{
        dislogType.value = 'add'
        whxdId.value = null
    }
    
    
}

//在组件挂载是加载数据
onMounted(() => {
    const savedData = localStorage.getItem('whdxData')
    if (savedData) {
        tableData.value =JSON.parse(savedData)
    }else{
        tableData.value = data //使用默认数据
    }
})

//添加删除成功功能以更新 localStorage
const deleteItem = (index) => {
    tableData.value.splice(index,1)
    localStorage.setItem('whxdData',JSON.stringify(tableData.value))
}

const submitForm = async (formEl) =>{
    if (!formEl) return
        console.log('formEl',formEl)
    await formEl.validate((valid,fields) => {
        if (valid) {
            console.log('submit!');
            console.log(ruleForm.value);

            //获取最大ID并自增
            const maxId =tableData.value.length > 0
            ? Math.max(...tableData.value.map(item => item.id || 0))
            :0
            //如果有id就编辑，没有id就新增
            if (whxdId.value) {
                 //如果有id查找索引，然后去修改数组对应得索引对的数据
                const index = tableData.value.findIndex(item => item.id === whxdId.value)
                tableData.value[index] = {
                    id:whxdId.value,
                    name:ruleForm.value.name,
                    address:ruleForm.value.address,
                    businessHours:`${ruleForm.value.startTime || ''} - ${ruleForm.value.endTime || ''}`,
                    url:ruleForm.value.url || [],
                    label:ruleForm.value.label || [],
                }
            }else{
                //新增通过push添加数据到loccalStorage
                tableData.value.push({
                id:maxId + 1,
                name:ruleForm.value.name,
                address:ruleForm.value.address,
                businessHours:`${ruleForm.value.startTime || ''} - ${ruleForm.value.endTime || ''}`,
                url: ruleForm.value.url || [],
                label: ruleForm.value.label || [],
                })
            }

            //添加到表格数据中
            // tableData.value.push(newData)
            //保存到localStorage
            localStorage.setItem('whxdData',JSON.stringify(tableData.value))

            //初始化表单数据
            ruleForm.value = {
                name:'',
                address:'',
                startTime:'',
                endTime:'',
                urlList:[],
                label:[],
    
            }
            //关闭新增弹窗
            whxdVisible.value=false
        }else{
            console.log('error submit!',fields);
            
        }
    })
}
</script>

<style scoped lang="scss">
.box{
    padding: 20px;

    .header{
        display: flex;
        justify-content: flex-end;
    }
    .content{
        margin-top: 20px;

        .whxd-img{
            width: 100px;
            height: 100px;
        }
    }
}
</style>